package vn.com.epi.servlet;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/edit-file.html")
public class EditFileServlet extends HttpServlet {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    
    public EditFileServlet() {
        super();
    }
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.getRequestDispatcher("/WEB-INF/jsp/edit-file-form.jsp").forward(request, response);
    }

    
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        String path = request.getParameter("path");
        String content = request.getParameter("content");
        String fileName = "";
        String respond = "";
        try {
            File file = new File(path);
            if (file != null)
                fileName = file.getName();
            FileWriter fw = new FileWriter(file.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(content);
            bw.close();
            respond = file.getName() + " is updated";
        } catch (Exception e) {
            respond = "Can't edit this file: " + fileName;
        } finally {
            request.setAttribute("respond", respond);
            request.getRequestDispatcher("/WEB-INF/jsp/respond.jsp").forward(request, response);
        }
    }
}
